import { defineStore } from 'pinia'
import { reactive } from 'vue'
import { Selecter } from '@/api/global/types'

export interface SelectedItem {
  id: string
  name: string
}

interface Option {
  first: Selecter[]
}

// 定义一个函数来创建store的ID
function createSelectWithInputStoreId(id) {
  return `selectWithInput-${id}`
}

export const selectWithInputStore = (id) =>
  defineStore(createSelectWithInputStoreId(id), {
    state: () => ({
      limit: 1,
      isSelectDialogVisible: false,
      option: reactive({} as Option),
      selectedOption: reactive<Selecter[]>([])
    }),
    actions: {
      closeDialog() {
        this.isSelectDialogVisible = false
      },
      removeOption(code) {
        const index = this.selectedOption.findIndex((item) => item.code === code)
        if (index !== -1) {
          this.selectedOption.splice(index, 1)
        }
      },
      openDialog(event: MouseEvent) {
        event.stopPropagation() // 阻止事件冒泡
        // const res = await getListApi('d_nation')
        // this.option.first = res.data.d_nation
        this.isSelectDialogVisible = true
      },
      handleOptionSelect(selectedPartnerValues) {
        // 先清空已选，以避免重复
        this.selectedOption.splice(0, this.selectedOption.length)
        // 添加新的选项
        this.option.first?.forEach((item) => {
          if (selectedPartnerValues.includes(item.code)) {
            this.selectedOption.push(item)
          }
        })

        // await nextTick() // 等待 DOM 更新
        // // 手动触发表单验证
        // const elForm = await getElFormExpose()
        // elForm?.clearValidate(['partner']) // 清除partner字段的验证结果
        // elForm?.validateField('partner')
      },
      reset() {
        this.$reset()
      }
    }
  })()

export type SelectWithInputStoreType = ReturnType<typeof selectWithInputStore>
